<!-- 组织架构图左侧组件 -->

<template>
  <div class="left-list">
    <div @click="collapse" class="collapseBtn">
      <IconCaretRight v-if="isCollapsed" />
      <IconCaretLeft v-else />
    </div>
    <a-layout class="layout-demo">
      <a-layout-sider
        collapsible
        breakpoint="xl"
        hide-trigger
        :collapsed="isCollapsed"
        :collapsed-width="0"
        :style="{ width: '300px' }"
      >
        <div class="role-list" v-show="!isCollapsed">
          <div>
            <a-scrollbar style="height: 600px; overflow: auto">
              <div class="scroll">
                <div style="margin-bottom: 20px">
                  <div style="font-weight: bold; text-align: 18px">
                    {{ props.baseName }}
                  </div>
                  <div
                    style="
                      color: rgb(175, 183, 195);
                      text-align: 14px;
                      margin-top: 5px;
                    "
                  >
                    <span>{{ clientName }}</span
                    >/
                    <a-tooltip content="返回知识库列表">
                      <span>知识库</span>
                    </a-tooltip>
                  </div>
                </div>
                <a-input-search
                  allow-clear
                  class="search"
                  placeholder="输入分类名称"
                  v-model="searchVal"
                />
                <div
                  style="
                    display: flex;
                    justify-content: space-between;
                    margin-top: 20px;
                  "
                >
                  <a-button type="text" class="iconColor"
                    >目录 <template #icon> <icon-down /> </template></a-button
                  ><a-space>
                    <a-button type="text" class="iconColor">
                      <template #icon>
                        <icon-sync />
                      </template>
                    </a-button>
                    <a-dropdown @select="handleSelect">
                      <a-button type="text" class="iconColor">
                        <template #icon>
                          <icon-plus />
                        </template>
                      </a-button>
                      <template #content>
                        <a-doption @click="addParenFolder"
                          ><template #icon>
                            <icon-font type="icon-wenjianjia" :size="20" />
                          </template>
                          <template #default>创建文件夹</template></a-doption
                        >
                        <a-doption @click="goUploadFile(baseData)"
                          ><template #icon>
                            <icon-upload />
                          </template>
                          <template #default>上传文件</template></a-doption
                        >
                      </template>
                    </a-dropdown></a-space
                  >
                </div>

                <div class="scroll-content">
                  <a-tree
                    @select="selectNode"
                    v-if="baseData"
                    v-model:selected-keys="selectedKeys"
                    :fieldNames="{
                      key: 'id',
                      title: 'storeName',
                      children: 'children'
                    }"
                    :data="treeData"
                  >
                    <template #switcher-icon="node, { isLeaf }">
                      <icon-down v-if="!isLeaf" />
                      <icon-right v-if="isLeaf" />
                    </template>
                    <template #extra="nodeData">
                      <a-dropdown v-if="nodeData.fileName">
                        <icon-more
                          style="
                            position: absolute;
                            right: 8px;
                            font-size: 14px;
                            top: 10px;
                            color: #3370ff;
                          "
                        />
                        <template #content>
                          <a-doption>Option 1</a-doption>
                          <a-doption disabled>Option 2</a-doption>
                          <a-doption :value="{ value: 'Option3' }"
                            >Option 3</a-doption
                          >
                        </template>
                      </a-dropdown>
                      <a-dropdown v-else>
                        <icon-plus
                          style="
                            position: absolute;
                            right: 8px;
                            font-size: 14px;
                            top: 10px;
                            color: #3370ff;
                          "
                        />
                        <template #content>
                          <a-doption @click="addFolder(nodeData)">
                            <template #icon>
                              <icon-font type="icon-wenjianjia" :size="20" />
                            </template>
                            <template #default>创建文件夹</template></a-doption
                          >
                          <a-doption @click="goUploadFile(nodeData)">
                            <template #icon>
                              <icon-upload />
                            </template>
                            <template #default>上传文件</template></a-doption
                          >
                        </template>
                      </a-dropdown>
                    </template>
                  </a-tree>
                  <a-empty v-else description="暂无内容，点此新建" />
                </div>
              </div>
            </a-scrollbar>
          </div>
        </div>
      </a-layout-sider>
    </a-layout>
  </div>
  <FolderModal
    v-model:visible="modalVisible"
    :data="newBaseFolder"
    @addDocumentEmit="postKnowledgeBaseFolder"
  ></FolderModal>
  <UploadModal
    :userId="userId"
    ref="uploadRef"
    @hide="setHide"
    :route="uploadRoute"
    :folderInfo="folderInfo"
  ></UploadModal>
</template>

<script lang="ts" setup>
import clonedeep from 'lodash.clonedeep';
import { flatTreeWithChildren } from '@/utils/utils';
import FolderModal from './FolderModal.vue';
import UploadModal from './UploadModal.vue';
import mitter from '@/utils/mitt';
import {
  postknowledgeBase,
  getOneknowledgeBase,
  PostStorageDisk
} from '@/apis/document/documentCenter/index';
import mitt from 'mitt';

const route = useRoute();
const uploadRef = ref();
const storeName = route.query.storeName;
const storeId = route.query.id;
const uploadModalVisible = ref(false);
const userId = Number(localStorage.getItem('userId' as any));
const newBaseFolder = ref({});
let baseData = ref<any>({}); // 储存最初的树形数据
function treeToArray(tree: any) {
  //
  return tree.reduce((res: any, item: any) => {
    const { children, ...i } = item;
    return res.concat(
      i,
      children && children.length ? treeToArray(children) : []
    );
  }, []);
}

const setTreeData = (data: any) => {
  data.children.forEach((item: any) => {
    if (item.file) {
      item.file.forEach((ele: any) => {
        item.children.push({ ...ele, storeName: ele.useFileName, type: 1 });
      });
    }
    if (item.children) setTreeData(item);
  });
  return data;
};

const getData = async () => {
  try {
    const res = await getOneknowledgeBase({ id: storeId });
    baseData.value = setTreeData(res);
    console.log(222, baseData.value);
  } catch (err: unknown) {
    console.log(err);
  }
};

getData();
// import type { treeDataType } from '../../type';
const modalVisible = ref(false);
const emit = defineEmits(['clickTree']);
const props = withDefaults(
  defineProps<{
    data: any; // 是否显示对话框
    baseName: number; // 组织id
  }>(),
  {
    data: () => ({})
  }
);
let clientName = JSON.parse(localStorage.getItem('tenants') as any)[0]
  .clientName;
let searchVal = ref(''); // 搜索框
let selectedKeys = ref([]); // 选中的key

let expandKey: any = ref([]); // 储存当前搜索要展开的选项

// const searchData = (keyword: string) => {
//   const loop = (data: any) => {
//     const result: any = [];
//     data.forEach((item: any) => {
//       if (item.storeName.toLowerCase().indexOf(keyword.toLowerCase()) > -1) {
//         result.push({ ...item });
//       } else if (item.children) {
//         const filterData = loop(item.children);
//         if (filterData.length) {
//           result.push({
//             ...item,
//             children: filterData
//           });
//           expandKey.value.push(item.id);
//         }
//       }
//     });
//     return result;
//   };
//   return loop(baseData.value);
// };
let isCollapsed = ref(false); // 判断是否收起
const collapse = (collapsed: boolean) => {
  isCollapsed.value = !isCollapsed.value;
};
// /* 储存实时的属性数据 */
const treeData = computed(() => {
  return baseData.value.children;
});
const folderInfo = ref();
let path = ref([]);
const getTree = (data: any) => {
  if (data.parentId) {
    path.value.unshift(data.storeName);
    getTree(
      treeToArray([baseData.value]).filter((ele) => ele.id === data.parentId)[0]
    );
  } else if (data.parentId === 0) {
    path.value.unshift(data.storeName);
  }
};

const uploadRoute = ref('');
const goUploadFile = (nodeData: any) => {
  getTree(nodeData);
  uploadRoute.value = `${path.value.join('/')}/`;
  folderInfo.value = nodeData;
  uploadRef.value.visible = true;
};
// watch(
//   () => props.data,
//   (val) => {
//     console.log(112, val);
//     baseData.value = val.children ? val.children : [];
//     console.log(baseData.value);

//     // originTreeData.value = [val];
//     // selectedKeys.value = [originTreeData.value[0].id]; // 默认选中第一条数据
//     // // 如果是从组织机构列表跳转过来则直接显示对应id的数据
//     // if (props.id > 0) {
//     //   const temp = flatTreeWithChildren([val]).find(
//     //     (item: any) => item.id === props.id
//     //   );
//     //   // 直接用跳转过来组织的名字来搜索展开子树，然后将id赋值给selectedKeys
//     //   searchData(temp.department);
//     //   selectedKeys.value = [props.id];
//     //   emit('clickTree', temp);
//     // }
//   }
// );

const addFolder = (node: any) => {
  modalVisible.value = true;
  newBaseFolder.value = {
    parentId: node.id,
    parentName: node.storeName,
    storeName: '未命名文件夹',
    status: 1,
    knowledgeState: 1,
    userId
  };
};

const selectNode = (e: any, record: any) => {
  const getParentName = (id) => {
    return treeToArray([baseData.value]).filter((ele: any) => ele.id === id)[0]
      .storeName;
  };
  if (!record.node.fileName)
    mitter.emit('PreviewData', {
      ...record.node,
      previewType: 1,
      parentName: getParentName(record.node.parentId)
    });
  else
    mitter.emit('PreviewData', {
      ...record.node,
      previewType: 2,
      parentName: getParentName(record.node.fileBelongId)
    });
};
// 获取符合的数据
const getMatchIndex = (name: string): number => {
  if (!searchVal.value) return -1;
  return name.toLowerCase().indexOf(searchVal.value.toLowerCase()) as number;
};

// const getPath = (node: any, name: string) => {
//   console.log(2, node, name);
//   const path = [node.storeName];
//   let targetNode = null;
//   const traverseNode = (currentNode) => {
//     console.log(11, currentNode);
//     if (currentNode.storeName === name) {
//       console.log(33, currentNode);
//       targetNode = currentNode;
//       return;
//     }
//     if (currentNode.children && currentNode.children.length > 0) {
//       for (const child of currentNode.children) {
//         traverseNode(child);
//         if (targetNode) {
//           return;
//         }
//       }
//     }
//   };

//   traverseNode(node);
//   if (targetNode) {
//     while (targetNode.parentId !== 0) {
//       const parent = node.children.find(
//         (child) => child.id === targetNode.parentId
//       );
//       if (parent) {
//         console.log(1, path);
//         path.unshift(parent.storeName);
//         targetNode = parent;
//       } else {
//         break;
//       }
//     }
//   }
//   return `/${path.join('/')}/`;
// };

const addParenFolder = () => {
  modalVisible.value = true;
  newBaseFolder.value = {
    parentId: baseData.value.id,
    parentName: baseData.value.storeName,
    storeName: '未命名文件夹',
    status: 1,
    knowledgeState: 1,
    userId
  };
  console.log(newBaseFolder.value);
};

const postKnowledgeBaseFolder = async (val: any) => {
  try {
    console.log(val);
    await PostStorageDisk({ ...val });
    getData();
  } catch (err: unknown) {
    console.log(err);
  }
};

const setHide = () => {
  getData();
};
</script>

<style scoped lang="less">
.left-list {
  position: relative;
  background-color: rgba(250, 251, 251, 1);
  // padding: 0 15px;

  .collapseBtn {
    position: absolute;
    z-index: 9;
    top: 40%;
    right: 0px;
    height: 70px;
    width: 15px;
    background-color: #eee;
    line-height: 70px;
    text-align: center;
    cursor: pointer;
  }
  .layout-demo {
    height: 100%;
    background-color: rgba(250, 251, 251, 1);
    :deep(.arco-layout-sider) {
      max-width: 500px;
    }
  }
  .layout-sider {
    // width: 350px;
  }
  .arco-layout {
    flex: none !important;
  }
  .role-list {
    flex: 1;
    .scroll {
      padding: 10px;
      .search {
        background-color: #fff;
        height: 30px;
        border: 1px solid #ccc;
      }
    }
  }
}
:deep(.arco-layout-sider-trigger) {
  position: absolute;
  bottom: 0px;
  right: 20px;
  width: 20px !important;
  background: transparent;
}
:deep(.arco-tree-node-indent) {
  width: 0px;
  height: 0px;
}

:deep(.layout-demo),
:deep(.arco-layout-sider) {
  max-width: 500px;
}

.iconColor {
  color: rgba(23, 26, 29, 0.6);
}

:deep(.arco-tree-node-title-text) {
  text-overflow: ellipsis;
  overflow: hidden;
  word-break: break-all;
  white-space: nowrap;
  width: 150px;
}
</style>
